from scipy.special import comb  # 组合


def ave_Capital_Interest(Cap, R, N, isOut=False, calType=1):
    '''
    Parameters
    ----------
    Cap : float;本金/元
    R : float;月利率(月息)
    N : int;期限/月
    isOut : bool;是否输出月供情况(本金+利息)
    calType : int;计算方法(1=自研,2=百度)

    Returns
    -------
    each_CI : 月供本息(按等额本息方式)
    totalRepay : 还款总额
    totalInterest : 利息总额
    '''
    each_CI = 0.0  # 月供本息
    # 计算月供本息
    if calType == 1:  # 自研方法
        sumCR = 0.0
        for m in range(0, N):
            sumCR += comb(N, m) * (R ** (N - 1 - m))
        each_CI = Cap / sumCR + Cap * R
    elif calType == 2:  # 百度方法
        each_CI = Cap * (R * (1 + R) ** N) / ((1 + R) ** N - 1)
    else:
        print("请重新选择计算方法!")
    totalRepay = each_CI * N  # 还款总额
    totalInterest = totalRepay - Cap  # 利息总额

    # 计算月供情况(本金+利息)
    if isOut:
        sum_I = 0
        for m in range(1, N + 1):
            each_I = Cap * R  # 月供利息
            each_C = each_CI - each_I  # 月供本金
            Cap -= each_C
            print("第" + str(m) + "期," + "月供本金:%.2f" % each_C, "月供利息:%.2f" % each_I, "本金余额:%.2f" % Cap)
            sum_I = sum_I + each_I
        print("利息总额:%.2f" % sum_I)
    return each_CI, totalRepay, totalInterest


# 计算支付宝网商贷的月供及利息
# 网商贷采用“等额本金”的月供还款方式
def alipay_interest(loan, period):
    if period == 6:         # 分6期还款
        ave_Capital_Interest(loan, 0.0105, 6, True, 2)
    elif period == 12:      # 分12期还款
        ave_Capital_Interest(loan, 0.0105, 6, True, 2)
        remain_loan = loan/2    # 剩余还款金额

        ave_Capital_Interest(remain_loan, 0.0105, 6, True, 2)
    else:
        print("请输入正确的分期月数！")


# ave_Capital_Interest(47000, 0.01065, 12, True, 2)
alipay_interest(70000, 12)
